<template>
  <div 
    id="custom-gallery-panel" 
    class="custom-gallery-panel"
    :class="{ active: isActive }"
  >
    <div class="gallery-header">
      <div class="gallery-title">{{ galleryTitle }}</div>
      <button 
        id="close-gallery" 
        class="close-gallery"
        @click="toggleGallery"
        title="关闭"
      >
        <i class="fas fa-times"></i>
      </button>
    </div>
    <div class="gallery-content" id="gallery-content">
      <div v-if="loading" class="loading-container">
        <i class="fas fa-spinner fa-spin fa-3x"></i>
        <p>加载中...</p>
      </div>
      <div v-else-if="galleryItems.length === 0" class="empty-container">
        <p>没有找到VR内容</p>
      </div>
      <div v-else>
        <div 
          v-for="item in galleryItems" 
          :key="item.id"
          class="gallery-item"
          @click="handleGalleryItemClick(item)"
        >
          <img 
            :src="item.thumbnail || item.panorama" 
            :alt="item.name || 'VR全景图'"
            class="gallery-item-image"
          >
          <div class="gallery-item-caption">
            {{ item.name || '未命名' }}
          </div>
        </div>
      </div>
    </div>
    <div class="gallery-pagination">
      <button 
        id="gallery-prev-page" 
        class="gallery-page-btn prev-page-btn"
        :disabled="currentPage === 1"
        @click="showPreviousGalleryPage"
        title="上一页"
      >
        <i class="fas fa-chevron-left"></i>
      </button>
      <span id="gallery-page-info" class="gallery-page-info">
        第 {{ currentPage }} 页 / 共 {{ totalPages }} 页
      </span>
      <div id="gallery-page-numbers" class="gallery-page-numbers">
        <!-- 页码按钮将动态生成 -->
      </div>
      <button 
        id="gallery-next-page" 
        class="gallery-page-btn next-page-btn"
        :disabled="currentPage === totalPages"
        @click="showNextGalleryPage"
        title="下一页"
      >
        <i class="fas fa-chevron-right"></i>
      </button>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { vrAPI } from '../services/api.js'

export default {
  name: 'Gallery',
  setup() {
    // 状态管理
    const isActive = ref(false)
    const galleryItems = ref([])
    const currentPage = ref(1)
    const pageSize = ref(6)
    const totalItems = ref(0)
    const loading = ref(false)

    // 计算总页数
    const totalPages = computed(() => {
      return Math.ceil(totalItems.value / pageSize.value)
    })

    // 计算画廊标题
    const galleryTitle = computed(() => {
      if (loading.value) {
        return '加载中...'
      }
      return `VR全景图列表 (共 ${totalItems.value} 项)`
    })

    // 加载画廊项目
    const loadGalleryItems = async () => {
      loading.value = true
      try {
        const data = await vrAPI.getVRList(currentPage.value, pageSize.value)
        
        // 兼容接口返回的数据格式
        if (data && data.code === 200 && (data.rows || data.items)) {
          // 使用数据转换函数处理原始数据
          galleryItems.value = transformGalleryData(data.rows || data.items)
          totalItems.value = data.total || 0
        } else {
          galleryItems.value = []
          totalItems.value = 0
        }
      } catch (error) {
        console.error('加载画廊数据失败:', error)
        galleryItems.value = []
        totalItems.value = 0
      } finally {
        loading.value = false
      }
    }

    // 处理画廊项点击
    const handleGalleryItemClick = (item) => {
      // 发送事件给父组件，让父组件处理VR切换
      const event = new CustomEvent('gallery-item-click', { 
        detail: { item } 
      })
      window.dispatchEvent(event)
      
      // 关闭画廊
      toggleGallery()
    }

    // 数据转换函数 - 将API返回的数据转换为组件需要的格式
    const transformGalleryData = (rawItems) => {
      if (!Array.isArray(rawItems)) return []
      
      return rawItems.map(item => ({
        ...item,
        pointVrId: item.id, // 映射ID
        title: item.name,   // 映射标题
        imgUrl: item.thumbnail || item.panorama, // 映射图片URL
        // 移除字符串两端的空格，确保URL正确
        thumbnail: item.thumbnail ? item.thumbnail.trim() : '',
        panorama: item.panorama ? item.panorama.trim() : ''
      }))
    }

    // 显示上一页
    const showPreviousGalleryPage = () => {
      if (currentPage.value > 1) {
        currentPage.value--
        loadGalleryItems()
      }
    }

    // 显示下一页
    const showNextGalleryPage = () => {
      if (currentPage.value < totalPages.value) {
        currentPage.value++
        loadGalleryItems()
      }
    }

    // 切换画廊显示/隐藏
    const toggleGallery = () => {
      isActive.value = !isActive.value
      
      if (isActive.value) {
        // 显示画廊时，重置页码并加载数据
        currentPage.value = 1
        loadGalleryItems()
      }
    }

    // 初始化时设置全局函数
    onMounted(() => {
      // 挂载到全局，以便在需要时通过window访问
      window.toggleCustomGallery = toggleGallery
      window.handleGalleryItemClick = handleGalleryItemClick
      window.loadGalleryItems = loadGalleryItems
    })

    return {
      isActive,
      galleryItems,
      currentPage,
      pageSize,
      totalItems,
      totalPages,
      loading,
      galleryTitle,
      toggleGallery,
      loadGalleryItems,
      handleGalleryItemClick,
      showPreviousGalleryPage,
      showNextGalleryPage
    }
  }
}
</script>

<style scoped>
/* 画廊项目样式 - 与图标按钮相同的紫色主题 */
.gallery-item {
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(139, 92, 246, 0.2);
  border-radius: 12px;
  transition: all 0.3s;
  overflow: hidden;
  cursor: pointer;
  position: relative;
}

.gallery-item-image {
  width: 100%;
  height: 160px;
  object-fit: cover;
  display: block;
  transition: transform 0.5s ease;
}

.gallery-item-caption {
  padding: 12px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  font-size: 14px;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-weight: 500;
}

.gallery-item:hover {
  background: rgba(139, 92, 246, 0.1);
  border-color: rgba(139, 92, 246, 0.4);
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(139, 92, 246, 0.2);
}

.gallery-item:hover .gallery-item-image {
  transform: scale(1.05);
}

/* 分页按钮样式优化 */
.gallery-page-btn {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(139, 92, 246, 0.2);
  color: white;
  padding: 8px 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.gallery-page-btn:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.2);
  border-color: rgba(139, 92, 246, 0.4);
}

.gallery-page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 页码信息样式 */
.gallery-page-info {
  color: white;
  margin: 0 16px;
  font-size: 14px;
}

/* 加载状态样式优化 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: white;
  grid-column: 1 / -1;
}

/* 空状态样式优化 */
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: white;
  grid-column: 1 / -1;
}
</style>